package com.huiminpay.transaction.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huiminpay.common.cache.Cache;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.ErrorCode;
import com.huiminpay.transaction.api.dto.PayChannelDTO;
import com.huiminpay.transaction.api.dto.PayChannelParamDTO;
import com.huiminpay.transaction.api.dto.PlatformChannelDTO;
import com.huiminpay.transaction.api.service.IPlatformChannelService;
import com.huiminpay.transaction.convert.PayChannelParamConvert;
import com.huiminpay.transaction.convert.PlatformChannelConvert;
import com.huiminpay.transaction.entity.AppPlatformChannel;
import com.huiminpay.transaction.entity.PayChannelParam;
import com.huiminpay.transaction.entity.PlatformChannel;
import com.huiminpay.transaction.mapper.AppPlatformChannelMapper;
import com.huiminpay.transaction.mapper.PayChannelParamMapper;
import com.huiminpay.transaction.mapper.PlatformChannelMapper;
import com.huiminpay.transaction.mapper.PlatformPayChannelMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @ClassName : PlatformChannelServiceImpl
 * @Author : 阿泽
 * @Date: 2021/7/29 17:08
 * @Description : 平台服务
 */
@Service
public class PlatformChannelServiceImpl implements IPlatformChannelService {
    @Autowired
    PlatformChannelMapper platformChannelMapper;
    @Autowired
    AppPlatformChannelMapper appPlatformChannelMapper;
    @Autowired
    PlatformPayChannelMapper platformPayChannelMapper;
    @Autowired
    PayChannelParamMapper payChannelParamMapper;
    @Autowired
    Cache cache;

    private String keyPre="HUIMING:PAY:PARAM:";

    @Override
    public List<PlatformChannelDTO> findAllPlatformChannel() {
        List<PlatformChannel> platformChannels = platformChannelMapper.selectList(null);
        return PlatformChannelConvert.INSTANCE.listentity2listdto(platformChannels);
    }

    @Override
    public Object bindPlatformForApp(String appId, String platformChannel) throws BusinessException {
        //1.校验唯一性
        Integer integer = getAppPlatformChannelCnt(appId, platformChannel);
        if (integer>0){
            throw new BusinessException(CommonErrorCode.E_200003);
        }
        AppPlatformChannel appPlatformChannel = new AppPlatformChannel();
        appPlatformChannel.setAppId(appId);
        appPlatformChannel.setPlatformChannel(platformChannel);
        appPlatformChannelMapper.insert(appPlatformChannel);
        //2.持久化数据
        return "新增成功";
    }

    /**
     * 应用下有无该服务
     * @param appId
     * @param platformChannel
     * @return 返回值大于0 即为存在该服务
     */
    private Integer getAppPlatformChannelCnt(String appId, String platformChannel) {
        QueryWrapper<AppPlatformChannel> qw = new QueryWrapper<>();
        qw.lambda().eq(AppPlatformChannel::getAppId,appId).eq(AppPlatformChannel::getPlatformChannel,platformChannel);
        return appPlatformChannelMapper.selectCount(qw);
    }

    @Override
    public int queryAppBindPlatformChannel(String appId, String platformChannel) {
        return getAppPlatformChannelCnt(appId,platformChannel);
    }

    @Override
    public List<PayChannelDTO> queryPayChannelsByPlatfrom(String PlatformChannelCode) {
        return platformPayChannelMapper.queryPayChannelsByPlatfrom(PlatformChannelCode);
    }

    @Override
    public void savePayChannelParam(PayChannelParamDTO payChannelParam) throws BusinessException {
        //非空
        if (payChannelParam==null){
            throw new BusinessException(CommonErrorCode.E_200202);
        }
        //1.根据appId和PlatformChannelCode来查询AppPlatformChannelId
        AppPlatformChannel appPlatformChannel = getAppPlatformChannel(payChannelParam);
        if (appPlatformChannel==null){
            throw new BusinessException(CommonErrorCode.E_200210);
        }
        Long appPlatformChannelId = appPlatformChannel.getId();
        //2.根据AppPlatformChannelId和payChannel的唯一性来判断数据是否存在
        PayChannelParam payChannelParam1 = getPayChannelParam(payChannelParam, appPlatformChannel);
        //3.如果数据存在就更新 否则插入
        if (payChannelParam1==null){
            //没有就插入
            PayChannelParam payChannelParam2 = PayChannelParamConvert.INSTANCE.dto2entity(payChannelParam);
            payChannelParam2.setAppPlatformChannelId(appPlatformChannelId);
            payChannelParamMapper.insert(payChannelParam2);
        }else {
            //更新
            payChannelParam1.setChannelName(payChannelParam.getChannelName());//通道名
            payChannelParam1.setParam(payChannelParam.getParam());//支付参数
            payChannelParamMapper.updateById(payChannelParam1);
        }
        //更新缓存  产品名:模块名:功能名:业务参数  HUIMING:PAY:PARAM:应用ID:服务编码
        updateCache(payChannelParam);
    }

    private void updateCache(PayChannelParamDTO payChannelParam) {
        String key = keyPre+payChannelParam.getAppId()+":"+payChannelParam.getPlatformChannelCode();
        List<PayChannelParamDTO> payChannelParamDTOS = getPayChannelParamDTOS(payChannelParam.getAppId(), payChannelParam.getPlatformChannelCode());

        String value = JSON.toJSONString(payChannelParamDTOS);
        cache.set(key,value);
    }

    @Override
    public PayChannelParamDTO queryParamByAppPlatformAndPayChannel(String appId, String platformChannel, String payChannel) {
        //先从缓存中判断是否存在
        String key = keyPre+appId+":"+platformChannel;
        if(cache.exists(key)){
            //缓存存在
            String s = cache.get(key);
            //fastJson解析Json字符串
            List<PayChannelParamDTO> list = JSON.parseArray(s, PayChannelParamDTO.class);
            for (PayChannelParamDTO paramDTO:list){
                if (paramDTO.getPayChannel().equals(payChannel)){
                    return paramDTO;
                }
            }
        }
        //1.根据appId和PlatformChannelCode来查询AppPlatformChannelId
        PayChannelParamDTO payChannelParam = new PayChannelParamDTO();
        payChannelParam.setAppId(appId);
        payChannelParam.setPlatformChannelCode(platformChannel);
        payChannelParam.setPayChannel(payChannel);
        AppPlatformChannel appPlatformChannel = getAppPlatformChannel(payChannelParam);
        if (appPlatformChannel==null){
            throw new BusinessException(CommonErrorCode.E_200210);
        }
        Long appPlatformChannelId = appPlatformChannel.getId();
        //2.根据AppPlatformChannelId和payChannel的唯一性来判断数据是否存在
        PayChannelParam payChannelParam1 = getPayChannelParam(payChannelParam, appPlatformChannel);

        //更新缓存  产品名:模块名:功能名:业务参数  HUIMING:PAY:PARAM:应用ID:服务编码
        updateCache(payChannelParam);
        return PayChannelParamConvert.INSTANCE.entity2dto(payChannelParam1);

    }

    @Override
    public List<PayChannelParamDTO> queryPayChannelParam(String appId, String platformChannel) {
        //先从缓存中判断是否存在
        String key = keyPre+appId+":"+platformChannel;
        if(cache.exists(key)){
            //缓存存在
            String s = cache.get(key);
            //fastJson解析Json字符串
            return JSON.parseArray(s,PayChannelParamDTO.class);
        }else {
            List<PayChannelParamDTO> payChannelParamDTOS = getPayChannelParamDTOS(appId, platformChannel);
            cache.set(key,JSON.toJSONString(payChannelParamDTOS));
            return payChannelParamDTOS;
        }
//        return getPayChannelParamDTOS(appId, platformChannel);
    }

    /**
     * 得到全部支付参数 待调用
     * @param appId
     * @param platformChannel
     * @return
     */
    private List<PayChannelParamDTO> getPayChannelParamDTOS(String appId, String platformChannel) {

        //1.根据appId和PlatformChannelCode来查询AppPlatformChannelId
        PayChannelParamDTO payChannelParam = new PayChannelParamDTO();
        payChannelParam.setAppId(appId);
        payChannelParam.setPlatformChannelCode(platformChannel);
        AppPlatformChannel appPlatformChannel = getAppPlatformChannel(payChannelParam);
        if (appPlatformChannel==null){
            throw new BusinessException(CommonErrorCode.E_200210);
        }
        Long appPlatformChannelId = appPlatformChannel.getId();

        //根据id查询全部支付参数
        QueryWrapper<PayChannelParam> qw = new QueryWrapper<>();
        qw.lambda().eq(PayChannelParam::getAppPlatformChannelId,appPlatformChannelId);
        List<PayChannelParam> payChannelParams = payChannelParamMapper.selectList(qw);

        return PayChannelParamConvert.INSTANCE.listentity2listdto(payChannelParams);
    }

    /**
     * 得到指定支付渠道参数 待调用
     * @param payChannelParam
     * @param appPlatformChannel
     * @return
     */
    private PayChannelParam getPayChannelParam(PayChannelParamDTO payChannelParam, AppPlatformChannel appPlatformChannel) {
        QueryWrapper<PayChannelParam> qw = new QueryWrapper<>();
        qw.lambda().eq(PayChannelParam::getAppPlatformChannelId,appPlatformChannel)
                .eq(PayChannelParam::getPayChannel,payChannelParam.getPayChannel());
        return payChannelParamMapper.selectOne(qw);
    }

    /**
     * 得到应用绑定服务 待调用
     * @param payChannelParam
     * @return
     */
    private AppPlatformChannel getAppPlatformChannel(PayChannelParamDTO payChannelParam) {
        QueryWrapper<AppPlatformChannel> qw = new QueryWrapper<>();
        qw.lambda().eq(AppPlatformChannel::getAppId,payChannelParam.getAppId())
                .eq(AppPlatformChannel::getPlatformChannel,payChannelParam.getPlatformChannelCode());
        return appPlatformChannelMapper.selectOne(qw);
    }
}
